package com.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.web.domain.Category;
import com.web.service.BaseService;
import com.web.service.CategoryService;
import com.web.utils.BeanFactory;

/**
 * Servlet implementation class AdCategoryServlet
 */
@WebServlet("/adcategory") 
public class AdCategoryServlet extends BaseService {
	private static final long serialVersionUID = 1L;
	private CategoryService cs = (CategoryService) BeanFactory.getBean("CategoryService");
	/*
	 * 分类管理
	 */
	public String findCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			List<Category> cg = cs.findCategory();
			request.setAttribute("cg", cg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "admin/classify/classify.jsp";
	}
	
	/*
	 * 删除分类
	 */
	public String delCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			int cid = Integer.parseInt(request.getParameter("cid"));
			cs.delCategory(cid);
			String json ="{\"msg\":\"200\"}";
			response.getWriter().println(json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return null;
	}
	
	/*
	 * 修改
	 */
	public String updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			Category category = new Category();
			String cid=request.getParameter("cid");
			category.setCid(Integer.parseInt(cid));
			BeanUtils.populate(category, request.getParameterMap());
			
			cs.updateCategory(category);
			String json ="{\"msg\":\"200\"}";
			response.getWriter().println(json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public String addClassify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			Category category = new Category();
			BeanUtils.populate(category, request.getParameterMap());
			cs.addClassify(category);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return findCategory(request, response);
	}
}








